<template>
	<scroll-view scroll-y="true" class="folder">
		<view :class="disps != 'list'?'folder_icon':'folder_list'">
			<view v-for="(item,index) in fileList" :key="item._id"
				:class="value.includes(item)?'folder_item seted':'folder_item noseted'"
				@click.native.stop="$emit('handleItemClick', item)" @mouseenter.stop="rgrea(index)" @mouseleave="rgre">
				<view v-if="disps=='list'" class="clist">
					<view style="display: flex;justify-content: flex-start;align-items: center;">
						<view v-if="multiple" @click.stop="$emit('handleItemClick', item)"
							style="cursor: pointer;margin-right: 10px;padding: 1px 4px;border-radius: 3px;background-color:rgba(255, 255, 255, 1);border: 1px solid #333333">
							<i :class="value.includes(item)?'el-icon-check':'el-icon-plus'"
								:style="value.includes(item)?'color: #000;':'color: #fff;'"></i>
						</view>
						<uv-icon size="35" :name="getItemIcon(item)"></uv-icon>
						<view style="margin-left: 5px;">
							<view
								style="cursor: pointer;width: auto;display: flex;justify-content: flex-start;align-items: center;">
								<uv-text :lines="5" :text="cnName(item)"></uv-text>
							</view>
							<view style="display: flex;justify-content: flex-start;">
								<view style="font-size: 12px;color:#999">
									{{$uv.timeFormat(item.createdAt,'yyyy-mm-dd hh:MM')}}
								</view>
								<view v-if="item.kind === 'File'" style="margin-left: 10px;font-size: 12px;color:#999">
									{{formatFileSize(item.size)}}
								</view>
							</view>
						</view>
					</view>
					<view v-if="value.includes(item)||hover==index" style="display: flex;justify-content: flex-end;">
						<view class="btn" v-for="(ite,inde) in operation(item)" :key="inde"
							@click.native.stop="handleClick(ite,item)">
							<uv-icon size="20" v-if="ite.icon" :name="'/static/document/'+ite.icon+'.svg'"></uv-icon>
							<view v-else>
								{{ite.name}}
							</view>
						</view>
					</view>
				</view>
				<view v-else class="cicon">
					<view style="position: relative;">
						<uv-icon size="120" :name="getItemIcon(item)"></uv-icon>
						<view v-if="multiple" class="multiple" @click.stop="$emit('handleItemClick', item)">
							<i :class="value.includes(item)?'el-icon-check':'el-icon-plus'"
								:style="value.includes(item)?'color: #000;':'color: #fff;'"></i>
						</view>
						<view v-if="value.includes(item)||hover==index" class="clickIcon">
							<view class="clickIcon_item" v-for="(ite,inde) in operation(item)" :key="inde"
								@click.native.stop="handleClick(ite,item)">
								<uv-icon size="12" v-if="ite.icon"
									:name="'/static/document/'+ite.icon+'.svg'"></uv-icon>
							</view>
						</view>
					</view>
					<view style="cursor: pointer;width: auto;;display: flex;justify-content: flex-start;">
						<uv-text :lines="4" :text="cnName(item)"></uv-text>
					</view>
					<view style="display: flex;justify-content: flex-start;">
						<view style="font-size: 12px;color:#999">
							{{$uv.timeFormat(item.createdAt,'yyyy-mm-dd hh:MM')}}
						</view>
						<view v-if="item.kind === 'File'" style="margin-left: 5px;font-size: 12px;color:#999">
							{{formatFileSize(item.size)}}
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 重命名模态框 -->
		<view class="modal" v-if="showRenameModal">
			<view class="modal-content">
				<view class="modal-header">
					<view class="modal-title">重命名</view>
					<uv-button class="close-btn" @click="showRenameModal = false">&times;</uv-button>
				</view>
				<view class="form-group">
					<label class="form-label">新名称</label>
					<uv-input type="text" class="form-input" v-model="newItemName" :placeholder="selectedItem.name">
						<!-- <template v-slot:suffix>
							<uv-text :text="'.'+suffix" margin="0 0px 0 0" type="tips"></uv-text>
						</template> -->
					</uv-input>
				</view>
				<view class="modal-footer">
					<uv-button class="btn btn-outline" @click="showRenameModal = false">取消</uv-button>
					<uv-button class="btn btn-primary" @click="renameConfirm">确认</uv-button>
				</view>
			</view>
		</view>
		<uv-toast ref="toast"></uv-toast>
	</scroll-view>
</template>

<script>
	// 引入
	import tabbars from '@/components/tabbar/tabbar.vue';
	import config from '@/common/config'
	import {
		task,
		api,
		apiId,
		getScroll,
		scroll,
		delScroll,
		deleteItem,
		rename
	} from '@/common/api.js';
	import {
		download,
	} from '@/common/fun.js';
	export default {
		components: {
			// 注册组件
			tabbars
		},
		model: {
			prop: 'value', // 对应 props 的属性名
			event: 'input' // 触发事件名
		},
		props: {
			value: [Object, Array, String],
			fileList: [Object, Array, String],
			multiple: {
				type: Boolean,
				default: false,
			},
			disps: {
				validator(value) {
					// 这个值必须与下列字符串中的其中一个相匹配
					return ['list', 'icon'].includes(value)
				},
				default: 'list',
			},
			maxCount: {
				type: [Number, String],
			},
			title: {
				type: String,
				default: '分享'
			},
			folderStr: {
				type: String,
				default: ''
			},
			disabled: {
				type: Boolean,
				default: false
			},
			linkStyle: {
				type: String,
				default: ''
			},
			icon: {
				type: String,
				default: 'attach'
			},
			size: {
				type: String,
				default: '28'
			},
		},
		computed: {

		},
		data() {
			return {
				env: config.env,
				tabbar: config.tabbar,
				dialogVisible: true,
				showRenameModal: false,
				selectedItem: null,
				newItemName: '',
				suffix: '',
				shareShow: false,
				shareIndex: false,
				hover: false,
			}
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
			// #ifdef APP-NVUE
			this.scrollTop = e.detail.scrollTop;
			// #endif
		},
		methods: {
			operation(e) {
				let ope = [{
					name: '复制',
					icon: 'copy',
					click: 'copy'
				}, {
					name: '重命名',
					icon: 'rename',
					click: 'rename'
				}, {
					name: '下载',
					icon: 'download',
					click: 'download'
				}];

				let ope2 = [{
					name: '剪切',
					icon: 'paste',
					click: 'paste'
				}, {
					name: '删除',
					icon: 'delete',
					click: 'delete'
				}];
				// "kind": "File",
				if (e.en) {
					return [];
				}
				if (e.path.includes(this.folderStr)) {
					if (e.kind == 'File') {
						return ope;
					} else {
						return [];
					}
				}
				return [...ope, ...ope2];
			},
			cnName(e) {
				let name = e.name,
					mimeMap = {},
					Readend = '';
				mimeMap[this.folderStr] = '系统文件夹';
				if (mimeMap[e.name]) {
					name = mimeMap[e.name];
				}
				if (e.kind == "File" && e.path.includes(this.folderStr)) {
					name = 'RD_' + name;
				}
				return name;
			},
			rgrea(e) {
				if (this.shareShow == false) {
					this.hover = e;
				}
				var that = this;
				setTimeout(function() {
					that.shareIndex = true;
				}, 500);
			},
			rgre() {
				this.shareIndex = false;
				if (this.shareShow) return;
				this.hover = -1;
			},
			renameItem(item) {
				this.selectedItem = item;
				this.suffix = item.name.split('.').pop();
				this.newItemName = item.name.replaceAll('.' + this.suffix, '');
				this.showRenameModal = true;
			},
			async renameConfirm() {
				if (!this.newItemName.trim()) {
					this.$refs.toast.show({
						duration: '2000',
						message: "请输入新名称"
					});
					return;
				}

				try {
					await rename({
						id: this.selectedItem._id,
						newName: this.newItemName + '.' + this.suffix
					}, {
						custom: {
							auth: true,
							toast: true,
							catch: true,
						},
					});
					this.$refs.toast.show({
						duration: '2000',
						message: "重命名成功"
					});
					this.showRenameModal = false;
					this.$emit('loadFileList');
				} catch (error) {
					console.error('重命名失败:', error);
					this.$refs.toast.show({
						type: 'error',
						message: error.msg || '删除失败',
					})
				}
			},
			async deleteItem(item) {
				if (!confirm(`确定要删除"${item.name}"吗？`)) return;
				try {
					await deleteItem({
						id: item._id
					}, {
						custom: {
							auth: true,
							toast: true,
							catch: true,
						},
					});
					this.$refs.toast.show({
						duration: '2000',
						message: "删除成功"
					});
					this.$emit('loadFileList');
				} catch (error) {
					this.$refs.toast.show({
						type: 'error',
						message: error.msg || '删除失败',
					})
					console.error('Delete item failed:', error);
				}
			},
			getItemIcon(item) {
				if (item.icon) return item.icon;
				if (item.kind === 'Folder') {
					if (item.path.includes(this.folderStr)) {
						return '/static/document/folder-sys.svg'; // 普通文件夹图标
					} else {
						return '/static/document/folder.svg'; // 普通文件夹图标
					}
				} else {
					// 根据文件扩展名或mimeType返回不同的图标
					if (item.mimeType.includes('image')) {
						const ext = item.url.split('.').pop().toLowerCase();
						let arr = ['png', 'jpeg', 'jpg'];
						let paras = '';
						if (arr.includes(ext)) {
							paras = '?x-oss-process=image/resize,w_400,m_lfit'
						}
						return item.url + paras;
					}
					if (item.mimeType.includes('video')) {
						return item.url + `?x-oss-process=video/snapshot,t_3000,f_jpg,w_800,h_600`;
					}
					if (item.mimeType.includes('application')) {
						return `/static/document/zip.svg`;
					}
					return `/static/document/unknow.svg`; // 默认文件图标
				}
			},
			handleFilePreview(file) {
				// 根据文件类型决定是预览（如图片、PDF）还是下载
				console.error('handleFilePreview:', `/dpc/files/download/${file._id}`);
				download(`/dpc/files/download/${file._id}`);
				// uni.downloadFile({
				// 	url: `http://localhost:8080/dpc/files/download/${file._id}`, // 你的下载API
				// 	success: (res) => {
				// 		if (res.statusCode === 200) {
				// 			const filePath = res.tempFilePath;
				// 			uni.openDocument({
				// 				filePath: filePath,
				// 				success: function(res) {
				// 					console.log('打开文档成功');
				// 				},
				// 				fail: function(error) {
				// 					uni.showToast({
				// 						title: '无法打开文件',
				// 						icon: 'none'
				// 					});
				// 					console.error('Open document failed:', error);
				// 				}
				// 			});
				// 		}
				// 	},
				// 	fail: (error) => {
				// 		uni.showToast({
				// 			title: '下载失败',
				// 			icon: 'none'
				// 		});
				// 		console.error('Download file failed:', error);
				// 	}
				// });
			},
			handleClick(a, e) {
				if (a.click && a.click == 'download') {
					this.handleFilePreview(e)
				}
				if (a.click && a.click == 'delete') {
					this.deleteItem(e);
				}
				if (a.click && a.click == 'rename') {
					this.renameItem(e);
				}
				if (a.click && a.click == 'paste') {
					this.$emit('handleClick', e, a.click);
				}
				if (a.click && a.click == 'copy') {
					this.$emit('handleClick', e, a.click);
				}
				// this.$emit('handleItemClick', e);
				// console.log(a, e);
			},
			formatFileSize(size) {
				// 格式化文件大小显示
				if (!size) return '';
				if (size === 0) return '0 B';
				const k = 1024;
				const sizes = ['B', 'KB', 'MB', 'GB'];
				const i = Math.floor(Math.log(size) / Math.log(k));
				return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
			},
			routed(url) {
				uni.$uv.route({
					url: url,
					intercept(params, next) {
						console.log(params, next)
						uni.showLoading({
							title: '等待中...'
						})
						// 模拟处理等待
						setTimeout(() => {
							uni.hideLoading();
							next(true);
						}, 1000)
					}
				})
			}
		}
	}
</script>


<style scoped lang="scss">
	.folder {
		width: 100%;
		/* padding: 20rpx; */
		/* height: calc(99vh - 120rpx); */
		/* 根据实际情况调整高度 */

		/* display: flex;
		justify-content: space-between; */
		.folder_item {

			.clist {
				width: auto;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.btn {
					margin-left: 10px;
					cursor: pointer;
					font-size: 12px;
					display: flex;
					justify-content: space-between;
					align-items: center;
					border-bottom: 1px solid #FFF;
				}

				.btn:hover {
					color: #409EFF;
					border-bottom: 1px solid #409EFF;
				}
			}

			.cicon {
				.multiple {
					position: absolute;
					top: 10px;
					cursor: pointer;
					margin-right: 10px;
					padding: 1px 4px;
					border-radius: 3px;
					background-color: rgba(255, 255, 255, 1);
					border: 1px solid #333333
				}

				.clickIcon {
					position: absolute;
					left: 0px;
					right: 0px;
					bottom: 10px;
					display: flex;
					justify-content: space-around;
					flex-wrap: nowrap;

					.clickIcon_item {
						cursor: pointer;
						font-size: 12px;
						border-radius: 5px;
						padding: 2px 5px;
						background-color: rgba(255, 255, 255, 0.7);
					}
				}
			}
		}

		.folder_item:hover {
			background-color: #F0F9F7;
		}

		.seted {
			background-color: #eee;
		}



		.folder_icon {
			display: flex;
			justify-content: flex-start;
			align-items: flex-start;
			flex-wrap: wrap;

			.folder_item {
				width: 120px;
				margin: 2px 5rpx;
			}
		}

		.folder_list {


			.folder_item {
				padding: 1px 10px;
				border-top: 1px solid #EEEEEE;
			}
		}
	}

	.modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;

		.modal-content {
			background: white;
			border-radius: 8px;
			padding: 20px;
			width: 400px;
			max-width: 90%;
		}

		.modal-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20px;
		}

		.modal-title {
			font-size: 18px;
			font-weight: bold;
		}

		.close-btn {
			width: 50px;
			background: none;
			border: none;
			font-size: 20px;
			cursor: pointer;
			color: #999;
		}

		.form-group {
			margin-bottom: 15px;
		}

		.form-label {
			display: block;
			margin-bottom: 5px;
			font-weight: 500;
		}

		.modal-footer {
			display: flex;
			justify-content: flex-end;
			gap: 10px;
			margin-top: 20px;
		}

		@media (max-width: 768px) {

			.list-header,
			.list-item {
				grid-template-columns: 1fr;
				gap: 10px;
			}

			.item-actions {
				justify-content: flex-start;
			}
		}
	}
</style>